const config = require('./conf-found')
const log = require('./log-util')

const tencentcloud = require("tencentcloud-sdk-nodejs-dnspod");

const DnspodClient = tencentcloud.dnspod.v20210323.Client;

const clientConfig = {
    credential: {
        secretId: config.dnspodId,
        secretKey: config.dnspodSecretKey,
    },
    region: "",
    profile: {
        httpProfile: {
            endpoint: "dnspod.tencentcloudapi.com",
        },
    },
};

const client = new DnspodClient(clientConfig);

/**
 * 查询域名对应的记录 ID
 * @param sub 主机记录
 * @param domain 域名
 * @returns {Promise<RecordListItem>} Dnspod 返回的查询记录情况
 */
async function fetchRecord(sub, domain) {
    const data =  {Domain: domain, SubDomain: sub, IsExactSubDomain: true}
    const res = await client.DescribeRecordFilterList(data)
    return new Promise((resolve, reject) => {
        if (res && res.RecordList) {
            const record = res.RecordList[0]
            resolve(record)
        } else {
            reject(res)
            log.error()
        }
    })


}

/**
 * 修改记录
 * @param record 记录实例
 * @param ip 修改的 ip
 * @returns {Promise<void>}
 */
function modifyRecord(record, ip) {
    return new Promise((resolve, reject) => {
        record.FieldList[0].Value = ip
        client.ModifyRecordFields(record).then(() => {
            resolve()
        }, (error) => {
            reject(error)
        })
    })
}


async function subIpChange(ip) {

    for (const item of config.domains) {
        const domain = item[0]
        for (let j = 1; j < item.length; j++) {
            let res

            // 获取域名记录
            try {
                res = await fetchRecord(item[j], domain)
            } catch (e) {
                log.error('dnspod-support', JSON.stringify(e))
                return
            }

            if (!res) {
                log.error('dnspod-support',`${item[j]}.${domain} is not exists, please check conf or dnspod record`)
                return
            }

            // switch res to ModifyRecord API need supported
            const record = {
                Domain: domain,
                RecordId: res.RecordId,
                FieldList: [
                    {
                        Key: "value",
                        Value: res.Value
                    }
                ]
            }

            // 修改域名记录至对应IP
            try {
                await modifyRecord(record, ip)
                log.info('dnspod-support.js', `${item[j]}.${domain}: ${res.Value} => ${ip}`)
            } catch (e) {
                log.error('dnspod-support.js', e)
            }
        }
    }
}


// fetchRecord("@", "saycode.top").then(res => console.log(res))
module.exports = subIpChange